package com.carpedil.ms.service.impl;

import com.carpedil.ms.entity.User;
import com.carpedil.ms.mapper.UserMapper;
import com.carpedil.ms.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

/** @author Administrator */
@Service
@Slf4j
public class UserServiceImpl implements UserService {
  @Autowired private UserMapper userMapper;
  @Autowired private StringRedisTemplate redisTemplate;

  @Override
  public User checkUser(String username, String password) {
    return userMapper.checkUser(username, password);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public int saveUserCount(String username) {
    // 根据不同用户名,生成调用次数的key
    String limitKey = "LIMIT" + "_" + username;
    String limitNum = redisTemplate.opsForValue().get(limitKey);
    int limit = 0;
    if (limitNum == null) {
      // 第一次调用放入redis中设置为0
      redisTemplate.opsForValue().set(limitKey, "0", 3600, TimeUnit.SECONDS);
    } else {
      limit = Integer.parseInt(limitNum) + 1;
      redisTemplate.opsForValue().set(limitKey, String.valueOf(limit), 3600, TimeUnit.SECONDS);
    }
    return limit;
  }

  @Override
  public boolean getUserCount(String username) {
    String limitKey = "LIMIT" + "_" + username;
    String limitNum = redisTemplate.opsForValue().get(limitKey);
    if (limitNum == null) {
      log.error("该用户没有访问申请验证MD5值记录,疑似异常");
      return true;
    }
    // false 代表没有超过,true代表访问超过了限制 10次/用户
    return Integer.parseInt(limitNum) > 50;
  }

  @Override
  public User login(String username, String password) {
    // 验证用户信息
    User user = userMapper.login(username, password);
    if (user == null) {
      throw new RuntimeException("用户信息不存在");
    }
    return user;
  }
}
